package main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

import main.Game.GameState;

/**
 * What is this class' Single Responsibility?
 * @author Brian
 *
 */

public class MyJPanel extends JPanel{

	private static final long serialVersionUID = 1112318934616270020L;

	private int width, height;

	private long lastTime;//time of last frame
	private Game game;
	
	public MyJPanel(KeyListener keyListener, int width, int height, Game game){
		super();
		this.width = width;
		this.height = height;
		this.game = game;
		setPreferredSize(new Dimension(width,height));
		addKeyListener(keyListener);		
	}

    public void paintComponent (Graphics g)  {
    	
    	if(GameState.PLAYING == game.getState()){
    		game.updateGameObjects();

    	}else if(GameState.OVER == game.getState()){
    		
    	}

    	if(g instanceof Graphics2D){
    		Graphics2D g2d = (Graphics2D) g;
    		clearScreen(g2d);

    		g2d.setColor (Color.black);
    		g2d.drawString(getFps(), 420, 500); 
    		lastTime = System.currentTimeMillis();
            
            g2d.drawString(game.getScoreString(), 250,500);
          
            game.draw(g2d);
		
    	}
    }
    
    public void addNotify() {
        super.addNotify();
        requestFocus();
    }
    
    private void clearScreen(Graphics2D g2d){
        g2d.setColor (Color.white);
        g2d.fillRect (0 , 0, width, height); 
    }
    
    private String getFps(){
    	double fpsDisplay = 1000.0d/(System.currentTimeMillis()-lastTime);
		return String.format("FPS: %.1f",fpsDisplay);         	
    }
}
